from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from cookland.ricettario.models import Recipe
from django.contrib.auth.models import User
from cookland.ricettario.models import Comment
from cookland.ricettario.models import Ingredient
from cookland.ricettario.models import Category
from cookland.ricettario.models import Cuisine
from cookland.ricettario.models import Rate
from cookland.ricettario.models import Season
from django.contrib.auth.decorators import login_required
import re
from random import randint
from django.db.models import Q
import os

from django.template import RequestContext

import datetime
today = datetime.datetime.now().strftime('%m%d')
if today < '0321' or today > '1221':
    default_style = 'inverno'
elif today >= '0321' and today < '0621':
    default_style = 'primavera'
elif today >= '0621' and today < '0921':
    default_style = 'estate'
else:
    default_style = 'autunno'

# Create your views here.

# funzione per visualizzare una ricetta
def view_recipe(request, pk):
    style = request.session.get('style', default_style)
    print pk
    if request.POST:
        if request.POST['submit_action'] == "Aggiungi":
            if request.user.is_authenticated():
                c = Comment(
                        user = request.user,
                        recipe = Recipe.objects.get(pk=pk),
                        text = request.POST['comment']
                        )
                c.save()
            else:
                context = {}
                context['user'] = request.user
                context['error'] = 'Tu non hai diritto di commentare questa ricetta !!'
                context['style'] = style
                return render_to_response('error_form.htm', context)

        elif request.POST['submit_action'] == "Vota":
            if request.user.is_authenticated():
                rate_list = Rate.objects.filter(user=request.user)
                if len(rate_list) > 0:
                    rate_list = rate_list.filter(recipe=Recipe.objects.get(pk=pk))
                    if len(rate_list) > 0:
                        context = {}
                        context['user'] = request.user
                        context['error'] = "Tu hai gi&agrave; votato questa ricetta !!<br><br><a href='javascript:history.back();'>Torna indietro</a>"
                        context['style'] = style
                        return render_to_response('error_form.htm', context)
                    else:
                        rate = Rate(
                                user = request.user,
                                recipe = Recipe.objects.get(pk=pk),
                                )
                        rate.save()
                        re = Recipe.objects.get(pk=pk)
                        re.rates = re.rates+1
                        re.save()
                else:
                    rate = Rate(
                                user = request.user,
                                recipe = Recipe.objects.get(pk=pk),
                                )
                    rate.save()
                    re = Recipe.objects.get(pk=pk)
                    re.rates = re.rates+1
                    re.save()
            else:
                context = {}
                context['user'] = request.user
                context['error'] = 'Tu non hai diritto di votare questa ricetta !!'
                context['style'] = style
                return render_to_response('error_form.htm', context)

    r = Recipe.objects.get(pk=pk)
    ingres_obj = Ingredient.objects.filter(recipe=pk)
    comment_obj = Comment.objects.filter(recipe=pk)
    ingredienti = []
    comments = []
    media = 0
    for i in ingres_obj:
        ingredienti.append({"quantity": i.quantity, "name": i.name})
    for i in comment_obj:
        comments.append({"date": i.date, "user": i.user, "text": i.text})

    context = { 'style' : style,
                'nomericetta': r.name,
                'nomeautore': r.user,
                'categoriaricetta': r.category,
                'areageografica': r.cuisine,
                'ingredients': ingredienti,
                'preparazione': r.preparation,
                'tempo': r.time_required,
                'facilita': r.easy,
                'calorie': r.calories,
                'vino': r.wine,
                'voti': r.rates,
                'media': media,
                'comments': comments,
                'user': request.user,
                'satagione': r.season,
                'pk': r.id,
                'stagione': r.season }
    return render_to_response('view_recipe.htm', context)

# funzione per cercare una ricetta
def search_recipe(request):
    style = request.session.get('style', default_style)
    if request.POST:
        ricette = Recipe.objects.all()

        if int(request.POST['cucina']) != 0:
            ricette = ricette.filter(cuisine=request.POST['cucina'])

        if int(request.POST['categoria']) != 0:
            ricette = ricette.filter(category=request.POST['categoria'])
        
        if int(request.POST['stagione']) != 0:
            ricette = ricette.filter(category=request.POST['stagione'])
        
        #filter by parola chiave
        if request.POST['parola_chiave']:        
            parola = request.POST['parola_chiave']
            p = re.compile(parola, re.IGNORECASE)
            temp_ricette = []
            for i in ricette:
                ings = Ingredient.objects.filter(recipe=i)
                if p.search(i.name):
                    temp_ricette.append(i)
                else:
                    for j in ings:
                        if p.search(j.name):
                           temp_ricette.append(i)
                           break 
            ricette = temp_ricette
        
        #filter by vino
        if request.POST['vino']:        
            parola = request.POST['vino']
            p = re.compile(parola, re.IGNORECASE)
            temp_ricette = []
            for i in ricette:
                if p.search(i.wine):
                    temp_ricette.append(i)
            ricette = temp_ricette

        #filter by calorie
        if request.POST['calorie']:
            calorie = int(request.POST['calorie'])
            temp_ricette = []
            for i in ricette:
                if i.calories <= calorie:
                    temp_ricette.append(i)
            ricette = temp_ricette

        #filter by difficolta
        if int(request.POST['difficolta']) != 0:
            difficolta = int(request.POST['difficolta'])
            temp_ricette = []
            for i in ricette:
                if i.easy <= difficolta:
                    temp_ricette.append(i)
            ricette = temp_ricette

        #filter by tempo
        if int(request.POST['tempo']) != 0:
            tempo = int(request.POST['tempo'])
            temp_ricette = []
            if tempo == 61:
                for i in ricette:
                    if i.easy >= tempo:
                        temp_ricette.append(i)
            else:
                for i in ricette:
                    if i.easy <= tempo:
                        temp_ricette.append(i)
            ricette = temp_ricette        

        context = {}
        context['user'] = request.user
        context['style'] = style
        context['titolo'] = 'Risultato Ricerca'
        if len(ricette) > 0:
            array = []
            for i in ricette:
                array.append({"id": i.id, "name": i.name})
            context['ricette'] = array
        else:
            context['error'] = "Search result is empty !!"
        
        return render_to_response('recipe_list.htm',context)
        
    else:
        context = {}
        context['user'] = request.user
        cu_obj = Cuisine.objects.all()
        cuisines = []
        for i in cu_obj:
            cuisines.append({"id": i.id, "name": i.name})
        context['cuisine'] = cuisines

        ca_obj = Category.objects.all()
        categories = []
        for i in ca_obj:
            categories.append({"id": i.id, "name": i.name})
        context['category'] = categories

        se_obj = Season.objects.all()
        seasons = []
        for i in se_obj:
            seasons.append({"id": i.id, "name": i.name})
        context['season'] = seasons
        context['style'] = style

        return render_to_response('search_recipe.htm',context)

# funzione per inserire una ricetta
@login_required
def insert_recipe(request):
    if request.method == 'POST':
        r = Recipe( name = request.POST['ricetta'],
                    user = request.user,
                    category = Category.objects.get(pk=request.POST['categoria']),
                    time_required = request.POST['tempo'],
                    easy = request.POST['difficolta'],
                    calories = request.POST['calorie'],
                    rates = 0,
                    preparation = request.POST['preparazione'],
                    wine = request.POST['vino'],
                    cuisine = Cuisine.objects.get(pk=request.POST['cucina']),
                    season = Season.objects.get(pk=request.POST['stagione'])
                    )
        r.save()
        string = request.POST['ing_list']
        lines = string.split("\n")
        for l in lines:
            itams = l.split(" -> ")
            if len(itams) > 1 :
                i = Ingredient( recipe = r,
                                quantity = itams[0],
                                name = itams[1]
                                )
                i.save()
        return HttpResponseRedirect('/recipes/view/%s' % str(r.id))

    else:
        style = request.session.get('style', default_style)
        context = {}
        context['user'] = request.user
        context['style'] = style
        cu_obj = Cuisine.objects.all()
        cuisines = []
        for i in cu_obj:
            cuisines.append({"id": i.id, "name": i.name})
        context['cuisine'] = cuisines

        ca_obj = Category.objects.all()
        categories = []
        for i in ca_obj:
            categories.append({"id": i.id, "name": i.name})
        context['category'] = categories

        se_obj = Season.objects.all()
        seasons = []
        for i in se_obj:
            seasons.append({"id": i.id, "name": i.name})
        context['season'] = seasons
        context['array'] = [1,2,3,4,5]

        return render_to_response('recipe_form.htm',context)

#funzione vissualizza ricette di dato un user
def recipes_of_user(request, username):
    style = request.session.get('style', default_style)
    u = User.objects.get(username=username)
    r = Recipe.objects.filter(user=u)

    context = {}
    context['user'] = request.user
    context['style'] = style
    context['titolo'] = 'Elenco ricette di %s' % (request.user.username)
    if len(r) > 0:
        recipe_list = []
        for recipe in r:
            recipe_list.append({'id': recipe.id, 'name': recipe.name})
        context['ricette'] = recipe_list
    else:
        context['error'] = 'nessuna ricetta inserita'

    return render_to_response('recipe_list.htm', context)

#funzione per modificare una ricetta
@login_required
def modify_recipe(request, pk):
    if request.method == 'POST':
        recipe = Recipe.objects.get(pk=pk)
        ings = Ingredient.objects.filter(recipe=recipe)
        if ings:
            ings.delete()
        
        recipe.name = request.POST['ricetta']
        recipe.category = Category.objects.get(pk=request.POST['categoria'])
        recipe.time_required = request.POST['tempo']
        recipe.easy = request.POST['difficolta']
        recipe.calories = request.POST['calorie']
        recipe.preparation = request.POST['preparazione']
        recipe.wine = request.POST['vino']
        recipe.cuisine = Cuisine.objects.get(pk=request.POST['cucina'])
        recipe.season = Season.objects.get(pk=request.POST['stagione'])
        recipe.save()

        string = request.POST['ing_list']
        lines = string.split("\n")
        for l in lines:
            itams = l.split(" -> ")
            if len(itams) > 1 :
                i = Ingredient( recipe = recipe,
                                quantity = itams[0],
                                name = itams[1]
                                )
                i.save()
        return HttpResponseRedirect('/recipes/view/%s' % str(recipe.id))
    
    else:
        style = request.session.get('style', default_style)
        recipe = Recipe.objects.get(pk=pk)
        if recipe.user == request.user:
            context = { 'style' : style,
                        'nome': recipe.name,
                        'selec_cuisine': recipe.cuisine.name,
                        'selec_category': recipe.category.name,
                        'selec_season': recipe.season.name,
                        'preparazione': recipe.preparation,
                        'tempo': recipe.time_required,
                        'facilita': recipe.easy,
                        'calorie': recipe.calories,
                        'vino': recipe.wine,
                        'user': request.user,
                        }
            cu_obj = Cuisine.objects.all()
            cuisines = []
            for i in cu_obj:
                cuisines.append({"id": i.id, "name": i.name})
            context['cuisine'] = cuisines

            ca_obj = Category.objects.all()
            categories = []
            for i in ca_obj:
                categories.append({"id": i.id, "name": i.name})
            context['category'] = categories

            se_obj = Season.objects.all()
            seasons = []
            for i in se_obj:
                seasons.append({"id": i.id, "name": i.name})
            context['season'] = seasons
            context['array'] = [1,2,3,4,5]

            ingreds = Ingredient.objects.filter(recipe=recipe)
            print ingreds
            string = ""
            for i in ingreds:
                string = string + i.quantity + " -> " + i.name + "\n"
            context['list'] = string
            
            return render_to_response('recipe_form.htm', context)

        else:
            context = {}
            context['error'] = 'Tu non hai diritto di modificare questa ricetta !!'
            context['style'] = style
            context['user'] = request.user
            return render_to_response('error_form.htm', context)

#funzione per generare top ten
def top_ten(request):
    style = request.session.get('style', default_style)
    r_list = Recipe.objects.all().order_by('-rates')[:10]
    context = {}
    context['user'] = request.user
    context['style'] = style
    context['titolo'] = 'Top Ten'
    if len(r_list) > 0:
        recipe_list = []
        for recipe in r_list:
            recipe_list.append({'id': recipe.id, 'name': recipe.name})
        context['ricette'] = recipe_list
    else:
        context['error'] = 'nessuna ricetta inserita'
    return render_to_response('recipe_list.htm', context)

def menu(request, parameter):
    style = request.session.get('style', default_style)
    if parameter == 'generate_form':
        cuisine_list = Cuisine.objects.all()
        cuisine = []
        for c in cuisine_list:
            cuisine.append({'id': c.id, 'name': c.name})
        season_list = Season.objects.all()
        season = []
        for s in season_list:
            season.append({'id': s.id, 'name': s.name})
        if not request.method == 'POST':
            return render_to_response('genera_menu.htm', {'style': style, 'cuisine': cuisine, 'season': season, 'user': request.user})
        else:
            cuisine = request.POST['cucina']
            season = request.POST['stagione']
            categories = Category.objects.all()
            context = {'style': style, 'titolo': "Menu' generato"}
            menu_item = []
            for c in categories:
                if int(cuisine) > 0:
                    if int(season) > 0:
                        r_list = Recipe.objects.filter(cuisine = Cuisine.objects.get(id=cuisine), season = Season.objects.get(id=season), category = c)
                    else:
                        r_list = Recipe.objects.filter(cuisine = Cuisine.objects.get(id=cuisine), category = c)
                else:
                    if int(season) > 0:
                        r_list = Recipe.objects.filter(season = Season.objects.get(id=season), category = c)
                    else:
                        r_list = Recipe.objects.filter(category = c)
                if len(r_list):
                    recipe = r_list[randint(0, len(r_list)-1)]
                    menu_item.append({'category': c.name, 'id': recipe.id, 'name': recipe.name})
            context['menu_items'] = menu_item
            context['user'] = request.user
            return render_to_response('view_menu.htm', context)

    elif parameter == 'season':
        season = Season.objects.get( name = default_style )
        all_year = Season.objects.get( id = 5 )
        categories = Category.objects.all()
        context = {'style': style, 'titolo': "Menu' di stagione"}
        menu_item = []
        for c in categories:
            r_list = Recipe.objects.filter(Q(season = season) | Q(season = all_year), category = c)
            if len(r_list):
                recipe = r_list[randint(0, len(r_list)-1)]
                menu_item.append({'category': c.name, 'id': recipe.id, 'name': recipe.name})
        context['menu_items'] = menu_item
        context['user'] = request.user
        return render_to_response('view_menu.htm', context)

    elif parameter == 'day':
        try:
            f = open('/django/cookland/menu_of_day.dat', 'r')
        except:
            os.system('touch /django/cookland/menu_of_day.dat')
            os.system("echo '1' > /django/cookland/menu_of_day.dat")
            f = open('/django/cookland/menu_of_day.dat', 'r')
        
        file_lines = f.readlines()
        date = file_lines[0]

        menu_item = []
        if date != datetime.datetime.now().strftime('%d-%m-%Y'):
            f.close()
            f = open('/django/cookland/menu_of_day.dat', 'w')
            f.write(str(datetime.datetime.now().strftime('%d-%m-%Y')))
            season = Season.objects.get( name = default_style )
            all_year = Season.objects.get( id = 5 )
            categories = Category.objects.all()
            context = {'style': style, 'titolo': "Menu' del giorno"}
            
            for c in categories:
                r_list = Recipe.objects.filter(Q(season = season) | Q(season = all_year), category = c)
                if len(r_list):
                    recipe = r_list[randint(0, len(r_list)-1)]
                    menu_item.append({'category': c.name, 'id': recipe.id, 'name': recipe.name})
                    f.write(("\n%s") % (str(recipe.id)))
        if len(menu_item):       
            context["menu_items"]=menu_item
        else:
            for l in f.readlines():
                if l[2]!="-":
                    recipe=Recipe.objects.get(id=int(l))
                    c=recipe.category        
                    menu_item.append({'category': c.name, 'id': recipe.id, 'name': recipe.name})
        context['user'] = request.user
        context["menu_items"]=menu_item         
        return render_to_response('view_menu.htm', context)
            

def recipe_of_month(request):
    style = request.session.get('style', default_style)
    r_list = Recipe.objects.filter(date__gt = datetime.datetime.now().strftime('%Y-%m-01'), date__lt = datetime.datetime.now().strftime('%Y-%m-32')).order_by('-rates')[:1]
    if len(r_list):
        recipe = r_list[randint(0, len(r_list)-1)]
        redirect = ('/recipes/view/%s/') % (str(recipe.id))
        return HttpResponseRedirect(redirect)
    else:
        return render_to_response('error_form.htm',{'user': request.user, 'style': style, 'error': 'Nessuna ricetta inserita nell\'ultimo mese'})
